package org.third.common.utils.rest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 *
 * Modifies an /v0 HTTP request to add the Content-Security-Policy header.
 */

public class ContentSecurityPolicyInterceptor extends HandlerInterceptorAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ContentSecurityPolicyInterceptor.class);

    private static final String CONTENT_SECURITY_POLICY_VALUE = " default-src 'self' data: ; script-src 'self' 'unsafe-eval' data: 'unsafe-inline' ; frame-src 'self' data: ; style-src 'self' 'unsafe-inline' ";

    private static final String CONTENT_SECURITY_POLICY_KEY_IE = "X-Content-Security-Policy";
    private static final String CONTENT_SECURITY_POLICY_KEY = "Content-Security-Policy";


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setHeader(CONTENT_SECURITY_POLICY_KEY_IE , CONTENT_SECURITY_POLICY_VALUE);
        response.setHeader(CONTENT_SECURITY_POLICY_KEY, CONTENT_SECURITY_POLICY_VALUE);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }
}
